package com.loginregister.web.old; /**
 * @author wzm
 * @create 2023-05-04 14:28
 */


import com.loginregister.pojo.User;
import com.loginregister.service.UserService;
import com.loginregister.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
//Servlet一旦执行  执行service  然后分发方法  如果方法被子类重写只会执行子类的


    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //获取参数  封装对象 对比验证码  查询结果  存储结果返回
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //获取 用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //验证码
        String code = request.getParameter("checkCode");

        //获取存储在session中的验证码
        String seesioncode = (String) request.getSession().getAttribute("seesioncode");

        //对比验证  出错则返回
        if(!code.equalsIgnoreCase(seesioncode)){
            //对比失败
            request.setAttribute("reg_msg","验证码错误");
            request.getRequestDispatcher("/register.jsp").forward(request,response);
            return;//停止当前方法
        }

        //验证码正确
        boolean register = userService.register(new User(username, password));
        if(register){
            //注册成功去登录
            request.setAttribute("login_msg","恭喜，注册成功，请登录！");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }else{
            //注册失败
            request.setAttribute("reg_msg","数据同步错误，稍后重试！");
            request.getRequestDispatcher("/register.jsp").forward(request,response);
        }


    }
}
